﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace KZ400B
{


    public partial class AxleManager
    {
        /// <summary>
        /// 相对零位设置
        /// </summary>
        /// <param name="axleName"></param>
        /// <returns></returns>
        public static bool RelativeZero(string axleName)
        {
            if (!IsOpen)
            {
                return false;
            }
            if (AxleCacheManager.AxleList[axleName] != null)
            {
                if (AxleCacheManager.AxleList[axleName].AxleActionStatus.VZeroIsSeted)
                {
                    setState(
                string.Format("[{0}] 轴 设置相对零位命令失败:虚拟零位已经设定"
                        , axleName
                        ));
                    return false;
                }
            }
            string data = Protocol.Packet(
                Protocol.GetRelativeZeroString(axleName)
                );
            return sendData(data);
        }

         static void OnRelativeZeroRespond(ProtocolV2.UnpacketResult ur)
        {
            if (ur.Result
                    && ur.Action == AxleActions.RelativeZeroRespond

                    )
            {
                if (AxleCacheManager.AxleList.ContainsKey(ur.AxleName))
                {
                    AxleCacheManager.AxleList[ur.AxleName].AxleStatus = AxleStatus.Running;

                }
            }

            setState(
                string.Format("[{0}] 轴 设置相对零位命令响应 : {1} {2} "
                        , ur.AxleName
                        , ur.Result ? "正确" : "错误"
                        , ur.Result ? "-> 设置相对零位运行中 ... " : string.Empty
                        ));
        }

         static void OnRelativeZeroComplete(ProtocolV2.UnpacketResult ur)
        {
            if (ur.Result
                && ur.Action == AxleActions.RelativeZeroFinish

                )
            {

                AxleRunState.Instance[ur.AxleName] = false;
                if (AxleCacheManager.AxleList.ContainsKey(ur.AxleName))
                {
                    AxleCacheManager.AxleList[ur.AxleName].IsToZeroed = false;
                    AxleCacheManager.AxleList[ur.AxleName].RelativeZero = AxleCacheManager.AxleList[ur.AxleName].Position;
                    AxleCacheManager.Update(ur.AxleName);
                    //AxleManager.QueryPosition(ur.AxleName);
                }

            }
            setState(
                string.Format("[{0}] 轴 设置相对零位命令运行结束 : {1}"
                        , ur.AxleName
                        , ur.Result ? "正确" : "错误"
                        )
                        );
        }
    }
}
